﻿using System;
using System.Diagnostics;

namespace NetAssist.Diagnostics
{
  /// <summary>
  /// A Utility class for simple and accurate ad-hoc code timing.
  /// </summary>  
  public class QuickStopwatch : IDisposable
  {
#if TRACE

    System.Diagnostics.Stopwatch sw;
    string message;

    /// <summary>
    /// Instantiate a new QuickStopwatch with the default blank message.
    /// </summary>
    public QuickStopwatch()
      : this(string.Empty) { }

    /// <summary>
    /// Instantiate a new QuickStopwatch with a custom message.
    /// </summary>
    /// <param name="message">A custom message to emit when the timer is done.</param>
    public QuickStopwatch(string message)
    {
      this.message = message;
      sw = new System.Diagnostics.Stopwatch();
      sw.Start();
    }

    #region IDisposable Members

    /// <summary>
    /// Disposes the stop watch. Emitting timing results to the console.
    /// </summary>
    public void Dispose()
    {
      sw.Stop();
      if (string.IsNullOrEmpty(message))
        Trace.WriteLine(sw.Elapsed.TotalSeconds);
      else
        Trace.WriteLine(string.Format("{0}: {1} (seconds)", message, sw.Elapsed.TotalSeconds));
      GC.SuppressFinalize(this);
    }

    #endregion

#else
    public QuickStopwatch() { }
    public QuickStopwatch(string message) { }
    public void Dispose() { }
#endif
  }
}
